﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using Common.Utilities;
using OnlineVideos.UI;
using MarkHeath.StarRating;
using HtmlAgilityPack;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using OnlineVideos.View_Models;
using System.Threading;
using OnlineVideos.Entities;
using InsertIntoDataBase;
using System.Threading.Tasks;
using System.IO.IsolatedStorage;

namespace OnlineMovies.Views
{
    public class Properties
    {
       
        public string CategoryName
        {
            get;
            set;
        }
        public int CategoryID
        {
            get;
            set;
        }
    }
    public partial class AddNewMatch : PhoneApplicationPage
    {
        public List<Properties> CastList = new List<Properties>();
        public static string imagetype = string.Empty;
        public bool TaskNavigation = false;
        public AutoResetEvent auto = new AutoResetEvent(false);
        public static bool navigated = false;
        ShowDetail showdetail;
        double ratingvalue = 0.0;
        IDictionary<string, int> Dic = new Dictionary<string, int>();
        public AddNewMatch()
        {
            InitializeComponent();
            Loaded += AddNewMatch_Loaded;
        }

        void AddNewMatch_Loaded(object sender, RoutedEventArgs e)
        {
            LoadAds();
            if (Dic.Keys.Count == 0)
            {
              
                var cat = Constants.connection.Table<ShowCategories>().ToListAsync().Result.Select(i => new Properties { CategoryName = i.CategoryName, CategoryID = i.CategoryID }).ToList();
                foreach (var list in cat)
                {
                    if (!Dic.ContainsKey(list.CategoryName))
                        Dic.Add(list.CategoryName, list.CategoryID);
                }
               
            }
            type.Text = AppResources.Type + " Name";
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 2);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
       

        private void userlocalimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                Constants.navigation = true;
                imagetype = "LocalImage";
                PhotoChooserTask task = new PhotoChooserTask();
                task.Completed += task_Completed;
                task.Show();
                TaskNavigation = true;
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in userlocalimg_MouseLeftButtonDown_1 event In AddNewMatch.cs file.", ex);
            }
        }
        void task_Completed(object sender, PhotoResult e)
        {
            try
            {
                if (e.TaskResult == TaskResult.OK)
                {
                    Constants.UserImage1 = new BitmapImage();
                    Constants.UserImage1.SetSource(e.ChosenPhoto);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + tblkshowname.Text, UriKind.Relative));

                    });

                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in task_Completed event In AddNewMatch.cs file.", ex);
            }


        }
        private void useronlineimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                Constants.navigation = false;
                imagetype = "OnlineImage";
                WebClient wb = new WebClient();
                if (ResourceHelper.AppName == Apps.Online_Education.ToString())
                    wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text + " Subject", UriKind.Absolute));
                else if (ResourceHelper.AppName == Apps.DrivingTest.ToString())
                    wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text, UriKind.Absolute));
                else if (ResourceHelper.AppName == Apps.Cricket_Videos.ToString())
                    wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text + " Match", UriKind.Absolute));
                else
                    wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text + " Movie", UriKind.Absolute));
                wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in useronlineimg_MouseLeftButtonDown_1 event In AddNewMatch.cs file.", ex);
            }
        }
        void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {

                    string PageHtml = e.Result.ToString();
                    Constants.OnlineImageUrls.Clear();

                    Constants.OnlineImageUrls = GetImages(PageHtml);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                    });
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in wb_DownloadStringCompleted event In AddNewMatch.cs file.", ex);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                });
            }

        }
        public ObservableCollection<string> GetImages(string input)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(input);

                foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
                {
                    if (node.OuterHtml.Contains("src") || node.OuterHtml.Contains("data-src") || node.OuterHtml.Contains("dfr-src") || node.OuterHtml.Contains("deferredsrc") || node.OuterHtml.Contains("src2"))
                    {
                        if (((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["src2"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["src2"] : node.Attributes["data-src"] : node.Attributes["src"]).Value.StartsWith("http"))
                        {


                            list.Add(((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["src2"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["src2"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                        }

                    }
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in GetImages event In AddNewMatch.cs file.", ex);
            }
            return list;
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            Constants.OnlineImageUrls.Clear();
            Constants.UserImage1 = null;
            Constants.DownloadTimer.Start();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        
            try
            {
               
                if (TaskNavigation == false)
                {
                  
                    if (Constants.UserImage1 != null)
                    {

                        if (navigated == false && Constants.navigation == false)
                        {
                            navigated = true;
                            NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + tblkshowname.Text, UriKind.Relative));
                        }
                        else
                        {
                            navigated = false;
                            Constants.UIThread = true;
                            if (imagetype == "LocalImage")
                            {
                                userlocalimg.Source = ResourceHelper.getShowTileImage(tblkshowname.Text + ".jpg");
                                useronlineimg.Source = new BitmapImage(new Uri("/Images/fromonline.png", UriKind.RelativeOrAbsolute));
                            }
                            if (imagetype == "OnlineImage")
                            {
                                useronlineimg.Source = ResourceHelper.getShowTileImage(tblkshowname.Text + ".jpg");
                                userlocalimg.Source = new BitmapImage(new Uri("/Images/fromlocal.png", UriKind.RelativeOrAbsolute));
                            }

                            Constants.UIThread = false;
                            Constants.UserImage1 = null;
                        }

                    }
                    else
                        Constants.navigation = false;
                }
                else
                {
                    TaskNavigation = false;
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo event In AddNewMatch.cs file.", ex);
            }
        }
        private void btnsave_Click_1(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tblkshowname.Text))
            {
                valid.Visibility = Visibility.Collapsed;
              
                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
                InsertData<ShowList> insert = new InsertData<ShowList>();

                insert.ParameterList = new ShowList();

                insert.ParameterList.ShowID = (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.Status == "Custom").OrderByDescending(i => i.ShowID).FirstOrDefaultAsync()).Result != null) ? Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.Status == "Custom").OrderByDescending(i => i.ShowID).FirstOrDefaultAsync()).Result.ShowID + 1 : 1;
                insert.ParameterList.Title = tblkshowname.Text;
                insert.ParameterList.Rating = ratingvalue;
                insert.ParameterList.Status = "Custom";
                insert.ParameterList.CreatedDate = System.DateTime.Now;

              
                    insert.ParameterList.ReleaseDate = System.DateTime.Now.ToString();
                    insert.ParameterList.SubTitle = "English";
               
               
                if (!iso.FileExists("/Images/" + tblkshowname.Text + ".jpg"))
                    insert.ParameterList.TileImage = "Default.jpg";
                else
                    insert.ParameterList.TileImage = tblkshowname.Text + ".jpg";
              
                insert.Insert();
               
                    if (insert.ParameterList.ShowID == 1)
                    {
                        AppSettings.MinPersonID = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID > 1).OrderBy(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID;
                    }
              

                Constants.Description.Clear();
                Constants.OnlineImageUrls.Clear();
                Constants.DownloadTimer.Start();
                NavigationService.GoBack();
            }
           
            else
            {
                 valid.Visibility = Visibility.Visible;
               
            }
        }

        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        private void rating_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            StarRatingControl starratingcontrol = new StarRatingControl();
            starratingcontrol.Rating = rating.Rating;
            ratingvalue = (Convert.ToDouble(starratingcontrol.Rating) / 2);
        }
    }
}